package fw.mvc.config;

import java.io.File;
import java.io.IOException;
import java.util.*;

import org.jdom2.*;
import org.jdom2.xpath.*;
import org.jdom2.input.SAXBuilder;

/**
 * key: String(request path); 
 * value: ConfigDoMap( do config infos).
 * @author feng xu on 20140919.
 *
 */
public class ConfigMap extends HashMap<String, ConfigDoMap> {
	
	public ConfigMap(File xmlFile) throws JDOMException, IOException{
		SAXBuilder builder = new SAXBuilder();
		Document doc = builder.build(xmlFile);
		XPathFactory expr = XPathFactory.instance();
		
		Element root = doc.getRootElement();
		List<Element> doList = root.getChildren("do");
		doList.forEach((Element eldo) -> {
			String path = eldo.getAttributeValue("path");
			
			String formName = eldo.getAttributeValue("form");
			Element elForm = (Element) expr.compile("//form[@name='"+formName+"']")
					.evaluateFirst(doc);
			String formClass = elForm.getAttributeValue("class");
			
			String actionName = eldo.getAttributeValue("action");
			Element elAction = (Element) expr.compile("//action[@name='"+actionName+"']")
					.evaluateFirst(doc);
			String actionClass = elAction.getAttributeValue("class");
			
			ConfigDoMap doConfig = new ConfigDoMap();
			doConfig.setPath(path);
			doConfig.setFormClass(formClass);
			doConfig.setActionClass(actionClass);
			
			eldo.getChildren("forward").forEach((Element elfw) -> 
				doConfig.put(elfw.getAttributeValue("condition"), elfw.getAttributeValue("renderer"))
			);
			
			this.put(path, doConfig);
			}
		);
	}
	
	public String toString(){
		StringBuffer sb = new StringBuffer();
		this.forEach((path, doMap) -> sb.append(doMap.toString()).append("\n"));
		return sb.toString();
	}
}
